package com.qqt.csr.im.service.sensitiveword;

import com.qqt.csr.common.idempotent.Idempotent;
import com.qqt.csr.common.idempotent.RequestKeyParam;
import com.qqt.csr.common.utils.CacheKeyUtil;
import com.qqt.csr.common.utils.JsonUtil;
import com.qqt.csr.common.sensitiveword.SensitiveWordShowTypeEnum;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Optional;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qqt.csr.im.mapper.SensitiveWordRuleMapper;
import com.qqt.csr.im.entity.SensitiveWordRule;
@Service
public class SensitiveWordRuleService extends ServiceImpl<SensitiveWordRuleMapper, SensitiveWordRule> {
    @Autowired
    private RedissonClient redissonClient;

    /**
     * 设置显示规则
     * @param tenantId
     * @param showType
     */
    @Idempotent(model = "sw:rule:cfg:")
    public void setRuleConfig(@RequestKeyParam String tenantId, Integer showType){
        SensitiveWordRule dbData = this.lambdaQuery().select()
                .eq(SensitiveWordRule::getTenantId, tenantId)
                .one();
        if(dbData == null){
            dbData = new SensitiveWordRule();
            dbData.setTenantId(tenantId);
            dbData.setShowType(showType);
            this.save(dbData);
        }else{
            SensitiveWordRule updateData = new SensitiveWordRule();
            updateData.setId(dbData.getId());
            updateData.setShowType(showType);
            this.updateById(updateData);
        }

        dbData.setShowType(showType);
        String cacheKey = String.format(CacheKeyUtil.IM.SENSITIVE_WORD_RULE_KEY, tenantId);
        redissonClient.getBucket(cacheKey).setAsync(JsonUtil.toJson(dbData), Duration.of(CacheKeyUtil.EXPIRE_TIME_8H, ChronoUnit.MILLIS));

    }

    /**
     * 获取租户下的规则
     * @param tenantId
     * @return
     */
    public SensitiveWordRule getRuleConfig(String tenantId){
        String cacheKey = String.format(CacheKeyUtil.IM.SENSITIVE_WORD_RULE_KEY, tenantId);
        return Optional.ofNullable(redissonClient.getBucket(cacheKey).get())
                .map(Object::toString)
                .map(json -> JsonUtil.toObject(json, SensitiveWordRule.class))
                .orElseGet(()->{
                    SensitiveWordRule rule = this.lambdaQuery().select().eq(SensitiveWordRule::getTenantId, tenantId).one();
                    if(rule == null){
                        rule = SensitiveWordRule.builder().tenantId(tenantId).showType(SensitiveWordShowTypeEnum.ASTERISKS_DISPLAYED.getCode()).build();
                    }
                    redissonClient.getBucket(cacheKey).setAsync(JsonUtil.toJson(rule), Duration.of(CacheKeyUtil.EXPIRE_TIME_8H, ChronoUnit.MILLIS));
                    return rule;
                });
    }

}
